const { Controller } = require('egg');
const jwt = require('jsonwebtoken');

const getRandom = (min, max) => {
  return Math.round(min + Math.random() * (max - min));
};
const getRandomNum = len => {
  let code = '';
  while (code.length < len) {
    code += getRandom(0, 9);
  }
  return code;
};

class UserController extends Controller {
  async sendMessageCode() {
    const phone = this.ctx.query.phone;
    if (phone) {
      const code = getRandomNum(6);
      // 将code存储到session中，方便后面登录做对比，session是服务端的一种数据存储方案，数据是存储在服务端的
      this.ctx.session.sendCode = code;
      this.ctx.session.sendPhone = phone;
      this.ctx.body = {
        code: 1,
        message: `验证码已发生至手机${phone}短信,[${code}]`,
      };
    } else {
      this.ctx.throw(422, {
        code: 0,
        message: '请传递手机号',
      });
    }
  }
  async login() {
    const { ctx } = this;
    const {
      phone,
      code,
    } = ctx.request.body;
    const { sendCode, sendPhone } = ctx.session;
    if (sendCode === code && phone === sendPhone) {
      try {
        const res = await this.service.user.find({ phone });
        const token = jwt.sign({
          ...res,
        }, 'liuyu123456');
        ctx.body = {
          code: 1,
          message: '登录成功',
          token,
        };
      } catch (e) {
        ctx.throw(422, {
          code: 0,
          message: '用户未注册',
        });
      }
    } else {
      ctx.throw(422, {
        code: 0,
        message: '验证码错误',
      });
    }
  }
  async register() {
    const { ctx } = this;
    const {
      name,
      password,
    } = ctx.request.body;
    try {
      await this.service.user.insert({
        name,
        password,
      });
      ctx.body = {
        code: 1,
        message: '注册成功',
      };
    } catch (e) {
      ctx.throw(422, {
        code: 0,
        message: '注册失败',
      });
    }
  }
  async info() {
    const { ctx } = this;
    ctx.body = {
      code: 1,
      data: ctx.info,
    };
  }
}

module.exports = UserController;
